import os
from typing import Optional, List
from pathlib import Path

from ..models.preview import PreviewContent
from ..cache.memory_cache import MemoryCache
from .preview_utils import PreviewUtils

class FilePreviewManager:
    def __init__(self):
        self.cache = MemoryCache.get_instance()
        self.preview_utils = PreviewUtils()
        
    def get_preview(self, file_path: str) -> Optional[PreviewContent]:
        # 先从缓存获取
        cached_preview = self.cache.get(file_path)
        if cached_preview:
            return cached_preview
            
        # 创建新的预览
        try:
            file_stat = os.stat(file_path)
            file_type = self.preview_utils.get_file_type(file_path)
            
            preview_data = None
            if file_type == 'text':
                preview_data = self.preview_utils.create_text_preview(file_path)
            elif file_type == 'image':
                preview_data = self.preview_utils.create_image_preview(file_path)
            
            preview_content = PreviewContent(
                file_path=file_path,
                file_type=file_type,
                preview_data=preview_data,
                file_size=file_stat.st_size,
                modified_time=file_stat.st_mtime
            )
            
            # 存入缓存
            self.cache.set(file_path, preview_content)
            return preview_content
            
        except Exception as e:
            print(f"Error creating preview for {file_path}: {str(e)}")
            return None
    
    def get_directory_content(self, directory_path: str) -> List[PreviewContent]:
        try:
            contents = []
            for entry in os.scandir(directory_path):
                if entry.is_file():
                    preview = self.get_preview(entry.path)
                    if preview:
                        contents.append(preview)
            return contents
        except Exception as e:
            print(f"Error scanning directory {directory_path}: {str(e)}")
            return [] 